import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器：为每次请求自动附加本地存储中的 Bearer Token
api.interceptors.request.use(
  (config) => {
    try {
      const token = localStorage.getItem('access_token')
      if (token) {
        config.headers = config.headers || {}
        config.headers['Authorization'] = `Bearer ${token}`
      }
    } catch {}
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器：统一错误提示，兼容 msg 字段；遇到无效 Token 自动清理
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      const data = error.response.data || {}
      const status = error.response.status
      const message = data.error || data.message || data.msg || '请求失败'
      error.message = message

      // 对 401/422 等与 Token 有关的错误做兜底处理，避免旧 Token 反复报错
      if (status === 401 || status === 422) {
        const msg = String(message || '').toLowerCase()
        if (msg.includes('subject must be a string') || msg.includes('token')) {
          try { localStorage.removeItem('access_token') } catch {}
          try { delete api.defaults.headers.common['Authorization'] } catch {}
        }
      }
    } else if (error.request) {
      error.message = '网络连接失败，请检查网络设置'
    } else {
      error.message = error.message || '未知错误'
    }
    
    return Promise.reject(error)
  }
)

export default api
